import {
  loadingShow,
  loadingHide
} from "../../utils1/util";
import store from "../../store/index";
import create from "../../utils1/create";

create.Page(store, {
  use: ['isToken', "GroupInfo", "xxcount"],
  data: {
    logosrc:"",
    isPushEnabled: false,
    show: false, // 删除重复的show字段
    Hospitalphone: "17373023530",
    Hospital: '医林医疗',
    Hospitaladdress: "广东省广州市白云区钟落潭障岗村",
    images: [
      "../../static/backgrounds/1.jpg",
      "../../static/backgrounds/2.jpg",
      "../../static/backgrounds/3.jpg",
      "../../static/backgrounds/4.jpg"
    ],
    msg: "微信小程序数据1",
    input_class: "input1",
    a: -1,
    b: 2,
    array1: [1, 2, 3, 4, 5, 6],
    array2: [{
      name: "张三",
      age: 20,
      sex: "男",
      hobby: ["唱歌", "跳舞", "打球"]
    }, {
      name: "老六",
      age: 30,
      sex: "男"
    }],
    check: true
  },
  onPushSwitchChange: function (e) {
    const isPushEnabled = e.detail.value;
    this.setData({
      isPushEnabled: isPushEnabled,
    });

    // // 将新的设置保存到本地缓存
    // wx.setStorageSync('isPushEnabled', isPushEnabled);

    // 根据设置执行相应的操作
    if (isPushEnabled) {
      this.subscribeMessage()
      console.log('推送已开启');
      // 开启震动提示
      wx.vibrateShort({
        success() {
          console.log('短震动成功');
        },
        fail(err) {
          console.error('短震动失败', err);
        }
      })
      // 这里可以添加开启推送的逻辑
    } else {
      this.unsubscribeMessage()
      console.log('推送已关闭');
      // 这里可以添加关闭推送的逻辑
    }
  },
  unsubscribeMessage() {
    wx.openSetting({
      success: function (res) {
        console.log("res", res)
        wx.getSetting({
          withSubscriptions: true,
          success: (res) => {
            console.log("resd", res);
            // 检查用户授权状态
            if (res.authSetting['scope.userInfo'] == true) {
              console.log('用户已授权用户信息');
            } else {
              console.log('用户未授权用户信息');
            }
          }
        })
      },
      fail: function (err) {
        console.error('打开设置页面失败:', err);
      }
    });
  },
  subscribeMessage() {
    const tmplId = "hDjhqH6GtMZl94ES3U4AnbcafnblyZ3nnQqu1P3R8X4";
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (res.subscriptionsSetting) {
          const mainSwitch = res.subscriptionsSetting.mainSwitch;
          const itemSettings = res.subscriptionsSetting.itemSettings;
          const tmplIdState = itemSettings ? itemSettings[tmplId] : null;

          if (mainSwitch) {
            if (tmplIdState === 'accept') {
              this.showSuccessToast('已订阅');
            } else if (tmplIdState === 'reject' || tmplIdState === 'ban') {
              // 注意：通常用户无法取消通过 wx.requestSubscribeMessage 请求的订阅
              // 这里可以只是给用户一个提示，或者尝试其他方式引导用户
              this.showSuccessToast('您已拒绝或禁止接收该消息');
              this.unsubscribeMessage()
              // 如果确实需要再次请求订阅（注意微信的限制），可以使用 setTimeout
              setTimeout(() => {
                // 但请注意，如果用户之前拒绝了订阅，这里可能会失败
                this.requestSubscription(tmplId);
              }, 3000);
            } else {
              // 用户尚未对该模板消息做出选择，可以请求订阅
              this.requestSubscription(tmplId);
            }
          } else {
            // 用户关闭了订阅消息的总开关
            this.showSuccessToast('您已关闭订阅消息功能，请前往设置打开');
            // 通常不会在这里请求订阅，因为用户已经明确表示不希望接收消息
            // 但如果确实需要，可以注释掉下面的 setTimeout 调用前的条件判断
            // if (/* 某些条件 */) {
            this.unsubscribeMessage()
            setTimeout(() => {
              this.requestSubscription(tmplId);
            }, 3000);
            // }
          }
        } else {
          // 获取订阅消息设置失败
          console.error('获取订阅消息设置失败:', res);
          // 可以选择给用户一个错误提示，或者执行其他恢复操作
          this.showSuccessToast('获取订阅消息设置失败，请稍后再试');
        }
      },
      fail: (err) => {
        // 获取设置失败，处理错误
        console.error('获取设置失败:', err);
        // 可以选择给用户一个错误提示，或者执行其他恢复操作
        this.showSuccessToast('获取设置失败，请检查您的网络连接或稍后再试');
        // 通常不会在这里请求订阅，因为可能是更严重的错误导致失败
        // 但如果确实需要，可以取消下面的注释
        // this.requestSubscription(tmplId);
      }
    })
  },
  subscribeMessage1() {
    const tmplIds = "hDjhqH6GtMZl94ES3U4AnbcafnblyZ3nnQqu1P3R8X4";
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res);
        if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
          let itemSettings = res.subscriptionsSetting.itemSettings;
          if (itemSettings) {
            let moIdState = itemSettings[tmplIds];
            if (moIdState === 'accept') {
              // this.showSuccessToast('已订阅');
              this.setData({
                isPushEnabled: true,
              });
            } else if (moIdState === 'reject' || moIdState === 'ban') {
              this.setData({
                isPushEnabled: false,
              });
            }
          } else {
            this.setData({
              isPushEnabled: false,
            });
          }
        } else {
          this.setData({
            isPushEnabled: false,
          });
        }
      },
      fail: () => {

      }
    });
  },

  requestSubscription(tmplIds) {
    wx.showModal({
      title: '提示',
      content: '请授权开通服务通知',
      showCancel: true,
      success: (ress) => {
        if (ress.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: [tmplIds],
            success: (res) => {
              if (res[tmplIds] === 'accept') {
                this.showSuccessToast('消息订阅成功');
                this.setData({
                  isPushEnabled: true,
                });
              } else {
                // this.showSuccessToast('用户拒绝订阅');
                console.log('用户拒绝订阅');
                this.setData({
                  isPushEnabled: false,
                });
              }
            },
            fail: (er) => {
              // this.showSuccessToast('订阅失败');
              console.log("订阅失败 ", er);
              this.setData({
                isPushEnabled: false,
              });
            }
          });
        }
      }
    });
  },

  showSuccessToast(title) {
    wx.showToast({
      title: title,
      icon: 'success',
      duration: 2000
    });
  },
  phoneOn() {
    wx.showModal({
      title: '温馨提示',
      content: '跳转到电话拨打页面?',
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          const cmpTel = store.data.GroupInfo && store.data.GroupInfo.Cmp_Tel;
          if (cmpTel) {
            wx.makePhoneCall({
              phoneNumber: cmpTel, // 此号码仅用于测试
              success: (res) => {
                console.log(res);
                console.log("拨打电话成功！");
              },
              fail: (res) => {
                console.log(res);
                console.log("拨打电话失败！");
              }
            });
          } else {
            console.log("GroupInfo 或 Cmp_Tel 未定义");
          }

        }
      }
    })
  },
  docontent() {
    if (store.data.isToken != null) {
      wx.navigateTo({
        url: '/pages/content/content'
      });
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },
  myTouch(e) {
    console.log(e.currentTarget.dataset.msg);
    console.log(e.currentTarget.dataset.id);
    console.log("我被触碰了！！");
  },
  dl() {
    wx.redirectTo({
      url: '/pages/login/login'
    });
  },
  onLoad() {
    console.log("store", store)
    this.loadData();
    this.loadData1()
  },
  onShow() {
    console.log("store", store)
    this.loadData();
    this.loadData1()
    if (store.data.isToken != null) {
      this.subscribeMessage1()
    }
  },
  onReady() {
    this.loadData();
    this.loadData1()
  },
  onPullDownRefresh() {
    this.loadData();
    this.loadData1()
  },
  loadData() {
    loadingShow();
    if (store.data.isToken != null) {
      wx.request({
        url: store.data.globhttp + "GetGroupInfo",
        method: 'POST',
        header: {
          'content-type': 'application/json',
          "content-type": "application/x-www-form-urlencoded"
        },
        data: JSON.stringify({
          User_Id: store.data.infouser.User_Id,
          Token_Code: store.data.isToken
        }),
        success: (res) => {
          if (res.data.RltCode == 1) {
            store.data.GroupInfo = JSON.parse(res.data.RltData);
            console.log(store.data.GroupInfo);
          } else if (res.data.RltCode == 13) {
            store.setToken("setAdress");
          }
          loadingHide();
        },
        fail: () => {
          loadingHide();
        }
      });
    } else {
      setTimeout(() => {
        loadingHide();
      }, 500); // 假设数据加载需要2秒
    }
  },
  loadData1() {
    loadingShow();
    if (store.data.isToken != null) {
      wx.request({
        url: store.data.globhttp + "GetCheckReports_Count",
        method: 'POST',
        header: {
          'content-type': 'application/json',
          "content-type": "application/x-www-form-urlencoded"
        },
        data: JSON.stringify({
          User_Id: store.data.infouser.User_Id,
          Token_Code: store.data.isToken,
          Begin_Year: "",
          End_Year: ""
        }),
        success: (res) => {
          console.log("res",res)
          if (res.data.RltCode == 1) {
            store.data.xxcount = JSON.parse(res.data.RltData);
            console.log(store.data.xxcount);
          } else if (res.data.RltCode == 13) {
            store.setToken("xxcount");
          }
          loadingHide();
        },
        fail: () => {
          loadingHide();
        }
      });
    } else {
      setTimeout(() => {
        loadingHide();
      }, 500); // 假设数据加载需要2秒
    }
  }
});